#!/bin/bash

cd $(dirname $0)
CUR_SHELL_DIR=$(pwd)
CUR_SHELL_NAME=$(basename ${BASH_SOURCE})

#修改这里jar包名即可
JAR_NAME="RuYiAdmin-SpringBoot-0.0.1-SNAPSHOT.jar"
JAR_PATH=$CUR_SHELL_DIR/$JAR_NAME
CUR_DATE="$(date +%Y-%m-%d)"

#JAVA_MEM_OPTS=" -server -Xms1024m -Xmx1024m -XX:PermSize=128m"
JAVA_MEM_OPTS=""

#SPRING_PROFILES_ACTIV="-Dspring.profiles.active=dev"
SPRING_PROFILES_ACTIV=""

LOG_DIR=$CUR_SHELL_DIR/RuYiAdminLogs
LOG_INFO=$LOG_DIR/Info
LOG_PATH=$LOG_INFO/${CUR_DATE}.log

echo_help() {
  echo -e "syntax: sh $CUR_SHELL_NAME start|stop"
}
if [ -z $1 ]; then
  echo_help
  exit 1
fi
if [ ! -d "$LOG_DIR" ]; then
  mkdir "$LOG_DIR"
fi
if [ ! -d "$LOG_INFO" ]; then
  mkdir "$LOG_INFO"
fi
if [ ! -f "$LOG_PATH" ]; then
  touch "$LOG_INFO"
fi
if [ "$1" == "start" ]; then
  # check server
  PIDS=$(ps --no-heading -C java -f --width 1000 | grep $JAR_NAME | awk '{print $2}')
  if [ -n "$PIDS" ]; then
    echo -e "ERROR: The $JAR_NAME already started and the PID is ${PIDS}."
    exit 1
  fi
  echo "Starting the $JAR_NAME..."

  # start
  nohup java $JAVA_MEM_OPTS -jar $SPRING_PROFILES_ACTIV $JAR_PATH >>$LOG_PATH 2>&1 &

  COUNT=0
  while [ $COUNT -lt 1 ]; do
    sleep 1
    COUNT=$(ps --no-heading -C java -f --width 1000 | grep "$JAR_NAME" | awk '{print $2}' | wc -l)
    if [ $COUNT -gt 0 ]; then
      break
    fi
  done
  PIDS=$(ps --no-heading -C java -f --width 1000 | grep "$JAR_NAME" | awk '{print $2}')
  echo "${JAR_NAME} Started and the PID is ${PIDS}."
  echo "You can check the log file in ${LOG_PATH} for details."

elif [ "$1" == "stop" ]; then

  while true; do
    read -p "Do you wish to stop this program?" yn
    case $yn in
    [Yy]*)
      PIDS=$(ps --no-heading -C java -f --width 1000 | grep $JAR_NAME | awk '{print $2}')
      if [ -z "$PIDS" ]; then
        echo "ERROR:The $JAR_NAME does not started!"
        exit 1
      fi
      echo -e "Stopping the $JAR_NAME..."

      for PID in $PIDS; do
        kill $PID >/dev/null 2>&1
      done

      COUNT=0
      while [ $COUNT -lt 1 ]; do
        sleep 1
        COUNT=1
        for PID in $PIDS; do
          PID_EXIST=$(ps --no-heading -p $PID)
          if [ -n "$PID_EXIST" ]; then
            COUNT=0
            break
          fi
        done
      done

      echo -e "${JAR_NAME} Stopped and the PID is ${PIDS}."
      break
      ;;
    [Nn]*) exit ;;
    *) echo "Please answer yes or no." ;;
    esac
  done

else
  echo_help
  exit 1
fi

#增加可执行权限
#chmod u+x RuYiAdmin-SpringBoot.sh

#启动jar包
#./RuYiAdmin-SpringBoot.sh start

#停止 jar包
#./RuYiAdmin-SpringBoot.sh stop

#查看帮助
#./RuYiAdmin-SpringBoot.sh help

#查看运行情况
#cd RuYiAdminLogs
#cd Info
#cat Info.2022-xx-xx.log

#b./bin/bash^M: bad interpreter: No such file or directory
#vi RuYiAdmin-SpringBoot.sh
#: set ff=unix
